# -*- coding: utf-8 -*

__author__ = 'huangxiaoli'

'''
    监控服务器状态 存入redis
    监控指标：
        host
        time
        load avg
        memTotal
        memUsage
        memFree
'''
import redis
import json
import logging
import socket
import time
from conf import config, config_redis, config_redis_override

class mon:

    def getTime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

    def getHost(self):
        return socket.gethostname()

    def getLoadAvg(self):
        with open('/proc/loadavg') as load_open:
            a = load_open.read().split()[:3]
            return ','.join(a)

    def getMem(self):
        with open('/proc/meminfo') as mem_open:
            T = int(mem_open.readline().split()[1])
            F = int(mem_open.readline().split()[1])
            A = int(mem_open.readline().split()[1])
            B = int(mem_open.readline().split()[1])
            C = int(mem_open.readline().split()[1])
            return (T,F,A,B,C)

if __name__ == "__main__":
    # 日志文件配置
    logger = logging.getLogger('mylogger')
    formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
    fh = logging.FileHandler('logging_redis.log')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.INFO)

    logger.info('**服务器监控程序启动**')

    configs = config_redis.configs
    try:
        configs = config.merge(configs, config_redis_override.configs)
    except ImportError:
        # 日志记录
        logger.info('**import模块报错，请检测配置文件**')
        pass

    host=configs['redis']['host']
    port=configs['redis']['port']
    password = configs['redis']['password']

    r = redis.Redis(host=host, password=password, port=port)
    m = mon()

    while True:
        moniDt = {
            "host": m.getHost(),
            'time': m.getTime(),
            'load_avg': m.getLoadAvg(),
            'mem_total': m.getMem()[0],
            'mem_free': m.getMem()[1],
            'mem_available': m.getMem()[2],
            'mem_buffers': m.getMem()[3],
            'mem_cached': m.getMem()[4]
        }
        try:
            r.set(moniDt['host'],json.dumps(moniDt))
        except redis.RedisError:
            # 日志记录
            logger.info('**Redis模块报错，数据插入失败**')
            pass
        # 线程沉睡
        time.sleep(5)
    logger.removeHandler(fh)


